package com.qsmx.store.app.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.qsmx.store.app.R;
import com.qsmx.store.app.databinding.DelegateUploadBinding;
import com.qsmx.store.app.fusion.FusionCode;
import com.qsmx.store.app.util.CommonUtils;
import com.qsmx.store.app.util.DialogUtil;
import com.qsmx.store.app.util.DownloadUtil;
import com.qsmx.store.app.util.FileUtils;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.net.HttpUrl;
import com.qsmx.store.core.util.loader.AtmosLoader;
import com.qsmx.store.core.util.zxing.ZXingUtil;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class UploadDelegate extends AtmosDelegate {
    private Uri resultUri;
    private String upLoadPath = "";
    private final int REQUEST_CODE_OPEN_DOCUMENT = 1;
    private DelegateUploadBinding mBinding;

    @Override
    public Object setLayout() {
        return R.layout.delegate_upload;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        mBinding = DelegateUploadBinding.bind(rootView);
        mBinding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getSupportDelegate().pop();
            }
        });
        mBinding.btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (resultUri == null) {
                    DialogUtil.showErrorDialog(requireContext(), "请先选择文件", "确定");
                    return;
                }
                upLoadPath = "user/testapp" + "/" + FileUtils.getPath(requireContext(), resultUri).split("/")[FileUtils.getPath(requireContext(), resultUri).split("/").length - 1];
                OSS oss = CommonUtils.makeOSSService(getContext());
                PutObjectRequest put = new PutObjectRequest(FusionCode.API_OSS_BUCKET,
                        upLoadPath, FileUtils.getPath(requireContext(), resultUri));
                oss.asyncPutObject(put, mSaveCallback);
                AtmosLoader.showLoading(requireContext());
            }
        });
        mBinding.btnSelectFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBinding.tvSelectedFile.setText(getString(R.string.wait_select_file));
                mBinding.tvUploadedFile.setText(getString(R.string.wait_upload_file));
                UploadDelegatePermissionsDispatcher.startCheckUpdateWithCheck(UploadDelegate.this);
            }
        });
    }

    OSSCompletedCallback<PutObjectRequest, PutObjectResult> mSaveCallback = new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
        @Override
        public void onSuccess(PutObjectRequest putObjectRequest, final PutObjectResult result) {
            AtmosLoader.stopLoading();
            mHandler.sendEmptyMessage(0);

        }

        @Override
        public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
            AtmosLoader.stopLoading();
            mHandler.sendEmptyMessage(1);

        }
    };

    private Handler mHandler = new Handler(new Handler.Callback() {
        @SuppressLint("SetTextI18n")
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 0) {
                mBinding.tvUploadedFile.setText(String.format(getString(R.string.uploaded_file), HttpUrl.OSS_PATH + upLoadPath));
                mBinding.ivQrCode.setImageBitmap(ZXingUtil.generateQRCode(HttpUrl.OSS_PATH + upLoadPath));
            } else if (msg.what == 1) {
                mBinding.tvUploadedFile.setText("上传失败");
            }

            return false;
        }
    });


    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_DOCUMENT && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            resultUri = uri;
            String filePath = FileUtils.getPath(requireContext(), uri);
            mBinding.tvSelectedFile.setText(String.format(getString(R.string.selected_file), filePath));
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startCheckUpdate() {
        showFileChooser();
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileRational(PermissionRequest request) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UploadDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
